import { createSlice}  from "@reduxjs/toolkit"
const cart  =  createSlice({
    name:"cart",
    initialState:{
        //shuju 
        cart:JSON.parse(localStorage.getItem('cart')) || [],
        show:JSON.parse(localStorage.getItem('show')) || [],
    },
    //fangfa
    reducers:{
        // 添加
        add(state,actions){
            console.log(actions);
            const copycart = [...state.cart]
            let index = copycart.findIndex(item=>item.id == actions.payload.id)
            if(index != -1){
                copycart[index].num += 1
            }else{
                copycart.push(actions.payload)
            }
            localStorage.setItem('cart',JSON.stringify(copycart))
        },
        // 添加到收藏
        addLists(state,actions){
            console.log(actions);
            const copyshow = [...state.show]
            let index = copyshow.findIndex(item=>item.id == actions.payload.id)
            if(index != -1){
                alert('已收藏')
            }else{
                copyshow.push(actions.payload)
            }
            localStorage.setItem('show',JSON.stringify(copyshow))
        },
        // 单选
        ischecked(state,actions){
            console.log(actions);
            const copycart = [...state.cart]
            let index = copycart.findIndex(item=>item.id == actions.payload.id)
            copycart[index].flag = actions.payload.checked
            state.cart = copycart
        },
        // 全选反选
        checkAll(state,actions){
            const copycart = [...state.cart]
            copycart.forEach(item=>{
                item.flag = actions.payload
            })
            state.cart = copycart
        },
        // 删除
        del(state,actions){
            console.log(actions);
            const copycart = [...state.cart]
            let index = copycart.filter(item=>item.id == actions.payload.id)
            // console.log(index);
            copycart.splice(index,1)
            localStorage.setItem('cart',JSON.stringify(copycart))
        },
        // 加
        addNum(state,actions){
            const copycart = [...state.cart]
            let index = copycart.findIndex(item=>item.id == actions.payload.id)
            copycart[index].num += 1
            localStorage.setItem('cart',JSON.stringify(copycart))
        },
        // 减
        delNum(state,actions){
            const copycart = [...state.cart]
            let index = copycart.findIndex(item=>item.id == actions.payload.id)
            copycart[index].num -= 1
            localStorage.setItem('cart',JSON.stringify(copycart))
        }
        

    }
})
export  const {add,ischecked,checkAll,del,addLists,addNum,delNum}  =  cart.actions
export  default  cart